package cn.com.cdb.ldms.modules.system.components;

import cn.hutool.extra.spring.SpringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@Component
public class DynamicControllerFactory {
    // 改为静态方法
    public static Object createDynamicController(String path, RequestMethod method, AutoViewConfig config) throws Exception {
        ViewConfigGenerator configGenerator = SpringUtil.getBean("viewConfigGenerator");
        Object controller = new Object() {
            @ResponseBody
            public Map<String, Object> handleRequest() {
                try {
                    return configGenerator.generateConfig(config.value());
                } catch (Exception e) {
                }
                return new HashMap<>();
            }
        };

        // 需要静态方式获取handlerMapping
        RequestMappingHandlerMapping handlerMapping = SpringUtil.getBean(RequestMappingHandlerMapping.class);

        Method handlerMethod = controller.getClass().getMethod("handleRequest");
        RequestMappingInfo mappingInfo = RequestMappingInfo
                .paths(path)
                .methods(method)
                .build();

        handlerMapping.registerMapping(mappingInfo, controller, handlerMethod);
        return controller;
    }
}